import os,re,sys

DIR_PATH = os.path.abspath(os.path.dirname(os.path.realpath(__file__)))
PYGMENTS_PATH = os.path.join(DIR_PATH,'pygments.zip')

sys.path.insert(0,PYGMENTS_PATH)
from pygments import highlight
from pygments.lexers import get_lexer_by_name,guess_lexer,get_all_lexers,find_lexer_class
from pygments.formatters import HtmlFormatter
from pygments.styles import get_all_styles

re_source = re.compile(r"\[code lang='(?P<lang>\S+)'\s*(style='(?P<style>\S+)'){0,1}\](?P<source>.+?)\[/code\]",re.DOTALL)

divstyles = 'word-wrap:break-word;white-space: pre;border:1px solid #BBBBBB;font-size: 9pt;\
line-height:125%;margin:10px 0 10px 0;'
prestyles = "white-space:pre-wrap;white-space: -moz-pre-wrap;white-space: \
-pre-wrap;white-space: -o-pre-wrap;word-wrap: break-word;\
padding:0.99em;"

def makeHighlight(entry):
    matches = list(re_source.finditer(entry.content))
    index = 0
    for match in matches:
        try: 
            all = match.group(0)
            lang = match.group('lang') or 'text'
            style = match.group('style') or 'default'
            source = match.group('source')
            
            source = source.replace('<p>','').replace('</p>','\n').replace('&nbsp;',' ').\
                         replace('<br>','\n').replace('<br />','\n').replace('<br/>','\n').\
                         replace('<p/>','\n').\
                         replace('&lt;','<').replace('&gt;','>').replace('&amp;','&')
            try:
                lexer = get_lexer_by_name(lang)
            except:
                try:
                    lexer = guess_lexer(source)
                except:
                    lexer = get_lexer_by_name('text')
            
            formatatter = HtmlFormatter(style=style,
                            cssclass=style,
                            cssstyles = divstyles,
                            prestyles = prestyles,
                            noclasses = False,
                            lineanchors = 'code%d'%index,
                            lineseparator = '\n'
                            )
            newsource = highlight(source,lexer, formatatter)
            #css = '\n<style type="text/css">\n<!--'
            #css += (formatatter.get_style_defs('.'+style))
            #css += '-->\n</style>\n'
            entry.content = entry.content.replace(all, newsource)
            index += 1
        except:
            pass
        
from base import BasePublicPage

class HighLightPage(BasePublicPage):
    languages = [lexer[1][0] for lexer in get_all_lexers()]
    languages.sort()
    styles = list(get_all_styles())
    
    def get(self):
        html = self.render('highlight', {
                              'languages' : HighLightPage.languages,      
                              'styles'    : HighLightPage.styles,       
                              })
        self.response.out.write(html)
        
    def post(self):
        content = self.request.get('source', 'no code')
        lang = self.request.get('lang', 'python')
        style = self.request.get('style','default')
        newcontent,css = HighLightPage.makeHighlight(lang,style,content)
        html = self.render('highlight', {
                              'languages' : HighLightPage.languages,      
                              'styles'    : HighLightPage.styles,              
                              'newcontent': newcontent,   
                              'content'   : content,
                              'curlang'   : lang,
                              'curstyle'  : style,  
                              'css'       : css,  
                              })      
        self.response.out.write(html)                                          
        pass
    
    def m_list_pages(self):
        menu_pages= self.template_vals['menu_pages']  #from Base
        ret=''
        for page in menu_pages:
            if page.link == 'highlight':
                current= 'current_page_item'
            else:
                current= 'page_item'
            ret+='<li class="%s"><a href="%s" >%s</a></li>'%( current,self.blog.baseurl+"/"+page.link, page.title)
        return ret
    
    @staticmethod
    def makeHighlight(lang,style,content):
        lexer = get_lexer_by_name(lang)
        css = r'<style type="text/css"><!--'
        css += (HtmlFormatter(style=style,
                            cssstyles = divstyles,
                            prestyles = prestyles).get_style_defs('.highlight'))
        css += r'--></style>'  
        
        new = highlight(content,lexer, HtmlFormatter(style=style,
                                                     cssstyles = divstyles,
                                                     prestyles = prestyles))
        
        return new,css